/* New mrinfo version by Pascal Merindol 27/04/2010 (pascal.merindol@uclouvain.be)*/
/*
 * This tool requests configuration info from a multicast router
 * and prints the reply (if any).  Invoke it as:
 *
 * sudo ./merlinc IP.in router.out [radixTREE stopSET ASN] [serverIP]
 *
 * Older version written Wed Mar 24 1993 by Van Jacobson (adapted from the
 * multicast mapper written by Pavel Curtis).
 *
 * The lawyers insist we include the following UC copyright notice.
 * The mapper from which this is derived contained a Xerox copyright
 * notice which follows the UC one.  Try not to get depressed noting
 * that the legal gibberish is larger than the program.
 *
 * Copyright (c) 1993 Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the Computer Systems
 *	Engineering Group at Lawrence Berkeley Laboratory.
 * 4. Neither the name of the University nor of the Laboratory may be used
 *    to endorse or promote products derived from this software without
 *    specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ---------------------------------
 * Copyright (c) Xerox Corporation 1992. All rights reserved.
 *
 * License is granted to copy, to use, and to make and to use derivative works
 * for research and evaluation purposes, provided that Xerox is acknowledged
 * in all documentation pertaining to any such copy or derivative work. Xerox
 * grants no other licenses expressed or implied. The Xerox trade name should
 * not be used in any advertising without its written permission.
 *
 * XEROX CORPORATION MAKES NO REPRESENTATIONS CONCERNING EITHER THE
 * MERCHANTABILITY OF THIS SOFTWARE OR THE SUITABILITY OF THIS SOFTWARE FOR
 * ANY PARTICULAR PURPOSE.  The software is provided "as is" without express
 * or implied warranty of any kind.
 *
 * These notices must be retained in any copies of any part of this software.
 */

#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>

#include "patricia.h"

#include "jhash.h"
#include "list.h"

#include <time.h>

#include <sys/types.h>
#include <setjmp.h>

#include <netdb.h>
#include <sys/time.h>
#include "defs.h"
#include <arpa/inet.h>


#ifdef __STDC__
#include <stdarg.h>
#else
#include <varargs.h>
#endif

#ifdef BSD
#define INET_FMT(x,y) inet_fmt(x)
#define u_int32 unsigned int
#elif LINUX
#define INET_FMT(x,y) inet_fmt(x,y)
#endif

#define HT_LENGTH_A 50000 /* size of the alias hash tables */
#define HT_LENGTH_I 500000 /* size of the IP hash tables */
#define IP_SIZE 17 /*15+1+1*/

#define TIMEOUTDNS 1000000 /* DNS TIMER (1 sec / request) */

#ifdef OLDSKL
#define NBSLICE 500  /* FOR OLDSKL : 14h max without responses max ! */
#else
#define NBSLICE 5 /* NUMBER OF SLICES BEFORE THE END */
#endif

#ifdef OLDSKL
#define SLICETIME 100  /* FOR OLDSKL : 14h max without responses max ! */
#else
#define SLICETIME 5 /* TIME BETWEEN TWO FLUSH ATTEMPTS */
#endif

#define TIMEPROBE 500000 /* TIME BETWEEN TWO REC PROBES (0.25 sec / request => 0.5) */
#define TIMEPROBESTATIC 50000 /* TIME BETWEEN TWO STATIC PROBES (0.05 sec / request) */


#ifdef OLDSKL /* to link requests and replies */
#define TIMEOLDSKL 5
#define NBXP 1000

struct link{
	u_int32 IP_in;
	u_int32 IP_out;
	double diff;
};
#endif

#ifdef OLDSKL
		TIMEINTER = TIMEOLDSKL;
#else
		TIMEINTER = TIMEPROBE;
#endif

FILE * fdout; /* output file for flushing */
static volatile int glob_kill = 0; /* To exit the main loop */
int nb_slice; /* nb slice before expiration */

int sockfd; /* Socket descriptor of the TCP server*/
int ASN; /* The targeted ASN */
char IPserver[IP_SIZE]; /* The IP of the server */

static sigjmp_buf timeout_env; /*to skip DNS resolution*/

/* Hashtables */
struct list_head hashtable[HT_LENGTH_A]; //Router level (alias) info
struct list_head ALRD_SEEN[HT_LENGTH_I]; //IP alrd probed or seen

/* for aliasing (THE SON) */
struct conf{
	struct list_head list;
	u_int32 IP;//IP of reply
    struct neighbor_head * nlist;
    char type[7];//OS version + ...
    short flag; /*to see whether if the router can be flushed: 0-no change during the last 10 sec 1-change during the last 10 sec*/
    short alrdflush; /* in order to know if the router has been sent/flush */
};

/* for each seen IP (THE SON) */
struct confo{
	struct list_head list;
	u_int32 IP; /* IP */
	u_int32 checksum_data; /* checksum on the data: only for replying IP having a "conf struct" */
	struct chk_sum * head_chksum; /* for multipacket : only for replying IP having a "conf struct" */
	u_int32 first; /*  first chief of the alias: in case of fragmentation and desordering, or IP not given in the alias => avoid duplicate aliases */
	char * dns; /* THE DNS name */
};

/* one per left addr (THE SON) */
struct neighbor_head{
	u_int32 intgauche; /* left IP */
	struct droite * head_dr; /* list of right addr */
	struct neighbor_head * next; /* next left addr */
	char metricflags[25]; /* all multicast info */
};

/* one per right addr (THE SON)*/
struct droite{
	u_int32 intdroite;
	struct droite * next;
};

/* for fragmentation: avoid the reception of two times the same packet content (THE SON) */
struct chk_sum{
	u_int32 checksum_data;
	struct chk_sum * next;
};

/* for each seen/probed IP (THE FATHER) */
struct confp{
	struct list_head list;
	u_int32 IP; /* IP */
	char * dns; /* THE DNS name */
};

/* when nothing to do, resolve DNS (THE FATHER) */
struct dnschain{
 char name[IP_SIZE];
 u_int32 IP;
 struct dnschain * next;
};

/* for DNS (THE FATHER) */
int annoy;
//0 we wait
//1 we do not wait at all
//2 we wait a shorter time

/* for the lookup inside an AS (used by the son to stop the exploration recursion one hop after AS boundaries) (THE SON) */
patricia_tree_t * radix_tree;

/* to store data when pipes are full (THE SON) */
struct droite * head_iprec_son;
struct droite * tail_iprec_son;

struct droite * head_ipalias_son;
struct droite * tail_ipalias_son;

//**********for DNS TIMERS issue**************//
void handle_sigalrm () {/* break the DNS resolution */
	siglongjmp(timeout_env,1);
}

//****************put the DNS name of "IP" in "IPdst" using a "timeout" ********//
int tonametime (char * IP, char * IPdst){

	u_int32_t addr;

	struct hostent *e = NULL;
	struct in_addr in;

	addr = inet_addr(IP);

	if ( addr == 0)//0.0.0.0
		{
		 strcpy(IPdst,"local");
		 return 1;
		}

	if (sigsetjmp(timeout_env,1) != 0) {
		return 0;
	}

	alarm(1);
	/* dns request */
	e = gethostbyaddr((char *)&addr,sizeof(addr),AF_INET);
	/* cancel the alarm call */
	alarm(0);

	if(!annoy)
	usleep(TIMEPROBE);
	else if (annoy == 2)
	usleep(TIMEPROBESTATIC);

	if ( e == NULL) {// we loose
		in.s_addr = addr;
		sprintf(IPdst,"%s",inet_ntoa(in));
		return 1;
        } else {// we have it
		 sprintf(IPdst,"%s",e->h_name);
		 return 1;
						   }

}


u_int32	our_addr, target_addr = 0;	/* in NET order */
int     debug = 0;
int	nflag = 0;

int	target_level = 0;
vifi_t  numvifs; /* to keep loader happy */
				 /* (see COPY_TABLES macro called in kern.c) */

char *			inet_name __P((u_int32 addr));
void			ask __P((u_int32 dst));
void			ask2 __P((u_int32 dst));
int			get_number __P((int *var, int deflt, char ***pargv,
					int *pargc));
u_int32			host_addr __P((char *name));
void			usage __P((void));

/* to shut up -Wstrict-prototypes */
int			main __P((int argc, char *argv[]));


/*********************************/
/****FLUSH THE DATA & SEND IT*****/
/*********************************/

static void flush_data(int sig){

				if(sig == SIGINT){
				glob_kill = 1;
	            printf("WARNING : PRESS CTRL+Z if it does not stop (The sending process is busy)\n");
	            return;
								 }

				int i = 0;
				int sm = 0; /* some changes ?*/

				struct conf * routoy = NULL;
				struct neighbor_head * tmp = NULL;

				short sendy = 0;

				if(strcmp(IPserver,"")) /* we are in a connected mode */
				sendy = 1;

				/* the buffer for TCP connection */
				char router[100];
				strcpy(router,"");

				for (i=0;i<HT_LENGTH_A;i++)
				{
					routoy = NULL;

					if(&hashtable[i]){
					list_for_each_entry(routoy,&hashtable[i],list){
					if(routoy){
					if(!routoy->flag && !routoy->alrdflush){
					sm = 1;
					fprintf(fdout,"%s [%s]:\n",INET_FMT(routoy->IP, s1),routoy->type);
					fflush(fdout);

					if(sendy){
					sprintf(router,"%s [%s]:|",INET_FMT(routoy->IP, s1),routoy->type);
					send(sockfd,router,strlen(router),0);}

					tmp = routoy->nlist;

					while(tmp){
						//fprintf(fdout," %s",tmp->gauche);
						fprintf(fdout," %s",INET_FMT(tmp->intgauche, s1));
						fflush(fdout);

						if(sendy){//sprintf(router," %s",tmp->gauche);
						sprintf(router," %s",INET_FMT(tmp->intgauche, s1));
						send(sockfd,router,strlen(router),0);}

						if(tmp->head_dr){
						fprintf(fdout," -> %s %s\n",INET_FMT(tmp->head_dr->intdroite,s1),tmp->metricflags);
						fflush(fdout);

						if(sendy){sprintf(router," -> %s %s|",INET_FMT(tmp->head_dr->intdroite,s1),tmp->metricflags);
						send(sockfd,router,strlen(router),0);}

						struct droite * drsave = tmp->head_dr;
						tmp->head_dr = tmp->head_dr->next;
						free(drsave); /* remove right part */
										}

						while(tmp->head_dr)
						{
						fprintf(fdout," -> %s\n",INET_FMT(tmp->head_dr->intdroite,s1));
						fflush(fdout);

						if(sendy){sprintf(router," -> %s|",INET_FMT(tmp->head_dr->intdroite,s1));
						send(sockfd,router,strlen(router),0);}

						struct droite * drsave = tmp->head_dr;
						tmp->head_dr = tmp->head_dr->next;
						free(drsave); /* remove right part */
						}

						struct neighbor_head * leftsave = tmp;
						tmp = tmp->next;
						free(leftsave); /* remove left part */

					}

					if(sendy){
					strcpy(router,"*");
					send(sockfd,router,strlen(router),0);
					}

					/* "supress" the router*/
					routoy->alrdflush = 1;

					} else routoy->flag = 0; /* this router has slice time sec to be changed*/
					}
					else break;
					};

				}
				}

				if(!sm) /* no change */
				nb_slice ++;
				else nb_slice = 0; /* change */

				if(nb_slice > NBSLICE && sendy)/* if no changes during NBSLICE time slice */
				{

#ifdef noDNS
strcpy(router,"END|*");
#else
strcpy(router,"STEP2|*");
#endif

				int sd = send(sockfd,router,strlen(router),0);

				if(sd < 0)
				perror("send()");

				close(sockfd);
				}

				else if(nb_slice > NBSLICE)
				fclose(fdout);

				return;

}


void close_sock(){
	glob_kill = 1;/*kill the infinite loop*/
				}

char   *
inet_name(addr)
	u_int32  addr;
{
	struct hostent *e;
	struct in_addr in;

	if (addr == 0)
		return "local";

	if (nflag ||
	    (e = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET)) == NULL) {
		in.s_addr = addr;
		return (inet_ntoa(in));
	}
	return (e->h_name);
}

/*
 * Log errors and other messages to stderr, according to the severity of the
 * message and the current debug level.  For errors of severity LOG_ERR or
 * worse, terminate the program.
 */
#ifdef __STDC__
void
log(int severity, int syserr, char *format, ...)
{
	va_list ap;
	char    fmt[100];

	va_start(ap, format);
#else
void
log(severity, syserr, format, va_alist)
	int     severity, syserr;
	char   *format;
	va_dcl
{
	va_list ap;
	char    fmt[100];

	va_start(ap);
#endif
	switch (debug) {
	case 0:
		if (severity > LOG_WARNING)
			return;
	case 1:
		if (severity > LOG_NOTICE)
			return;
	case 2:
		if (severity > LOG_INFO)
			return;
	default:
		fmt[0] = '\0';
		if (severity == LOG_WARNING)
			strcat(fmt, "warning - ");
		strncat(fmt, format, 80);
		vfprintf(stderr, fmt, ap);
		if (syserr == 0)
			fprintf(stderr, "\n");
		else if (syserr < sys_nerr)
			fprintf(stderr, ": %s\n", sys_errlist[syserr]);
		else
			fprintf(stderr, ": errno %d\n", syserr);
	}

	if (severity <= LOG_ERR)
		exit(-1);
}

/*
 * Send a neighbors-list request.
 */
void
ask(dst)
	u_int32  dst;
{
	send_igmp(our_addr, dst, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS,
			htonl(MROUTED_LEVEL), 0);
}

void
ask2(dst)
	u_int32  dst;
{
	send_igmp(our_addr, dst, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2,
			htonl(MROUTED_LEVEL), 0);
}


void affich_data(u_char * p, u_char * ep){

	while (p < ep){
		printf("%u-",*p);
		p++;
	}
}

/*
 * Process an incoming neighbor-list message.
 */

void
myaccept_neighbors2(src, dst, p, datalen, level, datapipe, datapipenot, routo, my_hash)
	u_int32	src, dst, level, my_hash;
	u_char	*p;
	int     datalen;
	int datapipe[];
	int datapipenot[];
	struct conf * routo;
	/* first packet, print header */
{
	u_char *ep = p + datalen;
	u_int broken_cisco = ((level & 0xffff) == 0x020a); /* 10.2 */
	/* well, only possibly_broken_cisco, but that's too long to type. */

		u_int skip = 0;/* to deal with stupid 3.x */

		if ((level & 0xffff) == 0x0603 || (level & 0xffff) == 0x0403 || (level & 0xffff) == 0x0803); /* dumb 3.6, 3.4 and 3.8 */
		u_int broken_junip = 1;

		sprintf(routo->type,"%d.%d",(level & 0xff),((level >> 8) & 0xff));

		int svrl = 1;/* Am I generating a duplication ?*/
		//TO BE CHANGED !! test that for the next tool...

		close(datapipenot[0]);
		char noprobe[4];

		u_int32 source = src;
		memcpy(noprobe,&src,4);

		short wr = write(datapipenot[1],noprobe,4);

		if(wr < 0 && errno == EAGAIN)/* pipe is full */
		{
			perror("write pipe error:");
			fprintf(stderr,"IPALIAS - PIPE is full: %s (let's store it!)\n",inet_fmt(src,s1));
			fflush(stderr);

			struct droite * newdr = (struct droite *)malloc(sizeof(struct droite));
			memcpy(&(newdr->intdroite),noprobe,4);
			newdr->next = NULL; /* add at tail */

			if(!head_ipalias_son)
			{
			head_ipalias_son = newdr; /* the ll was empty */
			tail_ipalias_son = newdr;
			}
			else
			{
			tail_ipalias_son->next = newdr; /* add at the end */
			tail_ipalias_son = newdr;
			}
		}


#ifdef ASTARGET
int rec = continue_rec(p,datalen,level);
#elif INTERNET
int rec = 1;
#endif

	while (p < ep) {
		register u_char metric;
		register u_char thresh;
		register u_char flags;
		register int ncount;
		register u_int32 laddr = *(u_int32*)p;

		p += 4;
		metric = *p++;
		thresh = *p++;
		flags = *p++;
		ncount = *p++;

		if ((broken_cisco /*|| broken_junip*/) && ncount == 0)	/* dumb Ciscos */
			ncount = 1;
		if ((broken_cisco /*|| broken_junip*/) && ncount > 15)	/* dumb Ciscos */
			ncount = ncount & 0xf;

		if(broken_junip && ncount == 0)
		skip = 1;
		else skip = 0;
		/*LEFT PART*/

		char left[IP_SIZE];
		strcpy(left,INET_FMT(laddr, s1));

		if(!svrl){
		/*maybe already seen via another IP of reply => TEST IT */
		struct confo * alrs_routoy;
		int hashy = jhash_1word(laddr,0)%HT_LENGTH_I;
		int foundyy = 0;
		list_for_each_entry(alrs_routoy,&ALRD_SEEN[hashy],list){if(laddr == alrs_routoy->IP ){foundyy=1;break;}};

	   //We have already seen this addr : USE A HASH on DATA to confirm
	   //choose the alias to keep in memory (with the the minimum IP id)
	   //:: 14-32 example //FRAGMENTED response :: packets are de-ordered (or IPs in a alias appear in different order -> post-processing)
	   //if not :: svrl=1; and normal way

		if(foundyy)
		{

		//TEST with a hash function before considering this packet as a duplicate alias
		if(hash_test(alrs_routoy,my_hash)){
		//we have a duplicate: now, who is the winner ?

		if(src == alrs_routoy->first){svrl = 1;}/*nothing to do, we follow normal the process: the following of the reply with an identical IP...*/
		else if(src < alrs_routoy->first)/* I win: put myself instead of the old one and return*/
		{
			struct conf * looser;
			int hashette = jhash_1word(alrs_routoy->first,0)%HT_LENGTH_A;
			list_for_each_entry(looser,&ALRD_SEEN[hashette],list){if(looser->IP == alrs_routoy->first ){break;}};

			    looser->IP = src;/* I am the new leader*/
			 //   strcpy(looser->name,INET_FMT(src, s1));
			    alrs_routoy->first = src;

			    list_del(&routo->list);

			    svrl = 1;
			    return;

		}
		else {list_del(&routo->list);return;}/*I loose: remove myself and break the process*/
		}
		else svrl = 1;//we won't test this packet as a duplicate anymore

		} else {/* normal way */svrl = 1;}

		}

		if(skip){//the right IP does not exists
					struct neighbor_head * nh;
					nh = (struct neighbor_head *)malloc(sizeof(struct neighbor_head));
					//sprintf(nh->gauche,"%s",left);

					nh->intgauche = inet_addr(left);
					nh->next = routo->nlist;
					routo->nlist = nh;//add at the head (last in first...)

					sprintf(nh->metricflags,"[%d/%d", metric, thresh);
							if (flags & DVMRP_NF_TUNNEL)
							strcat(nh->metricflags,"/t");
							if (flags & DVMRP_NF_SRCRT)
							strcat(nh->metricflags,"/s");
							if (flags & DVMRP_NF_PIM)
							strcat(nh->metricflags,"/p");
							if (flags & DVMRP_NF_QUERIER)
							strcat(nh->metricflags,"/q");
							if (flags & DVMRP_NF_DISABLED)
							strcat(nh->metricflags,"/d");
							if (flags & DVMRP_NF_DOWN)
							strcat(nh->metricflags,"/o");
							if (flags & DVMRP_NF_LEAF)
							strcat(nh->metricflags,"/l");
							strcat(nh->metricflags,"]");

							//printf("**********>> %s\n",nh->metricflags);
							//fflush(stdout);

					struct droite * dr = (struct droite *)malloc(sizeof(struct droite));

				//	sprintf(dr->droite,"%s","#");

					dr->intdroite = 0;
					dr->next = NULL;
					nh->head_dr = dr;//add at the head (last in first...)

		}

		else{//normal case
		struct neighbor_head * nh;
		nh = (struct neighbor_head *)malloc(sizeof(struct neighbor_head));
		//sprintf(nh->gauche,"%s",left);

		nh->intgauche = inet_addr(left);
		nh->head_dr = NULL;

		nh->next = routo->nlist;
		routo->nlist = nh;//add at the head (last in first...)

		/* multicast infos */
		sprintf(nh->metricflags,"[%d/%d", metric, thresh);
		if (flags & DVMRP_NF_TUNNEL)
		strcat(nh->metricflags,"/t");
		if (flags & DVMRP_NF_SRCRT)
		strcat(nh->metricflags,"/s");
		if (flags & DVMRP_NF_PIM)
		strcat(nh->metricflags,"/p");
		if (flags & DVMRP_NF_QUERIER)
		strcat(nh->metricflags,"/q");
		if (flags & DVMRP_NF_DISABLED)
		strcat(nh->metricflags,"/d");
		if (flags & DVMRP_NF_DOWN)
		strcat(nh->metricflags,"/o");
		if (flags & DVMRP_NF_LEAF)
		strcat(nh->metricflags,"/l");
		strcat(nh->metricflags,"]");


		/*mark left address as already probed*/
		if(laddr != src && routable(left)){/* The normal way: no duplicate */

					struct confo * alrs_routoy; /* we won't send that info to the father and mark as already seen if we have already do it*/
					int hashy = jhash_1word(laddr,0)%HT_LENGTH_I;
					int foundyy = 0;
					list_for_each_entry(alrs_routoy,&ALRD_SEEN[hashy],list){if(laddr == alrs_routoy->IP ){foundyy=1;break;}};

					if(foundyy)
					alrs_routoy->first = src; /* I am the (new) leader of this IP/alias */
					else
					{

			struct confo * router = (struct confo *)malloc(sizeof(struct confo));//put in ALRD SEEN
			int hash = jhash_1word(laddr,0)%HT_LENGTH_I;
			router->IP = laddr;
			router->first = src; /* I am the current winner*/

			list_add(&router->list,&ALRD_SEEN[hash]);

				close(datapipenot[0]);
				char noprobe[4];

				u_int32 lad = laddr;
				memcpy(noprobe,&lad,4);

				short wr = write(datapipenot[1],noprobe,4);

						if(wr < 0 && errno == EAGAIN)/* pipe is full */
						{
							perror("write pipe error:");
							fprintf(stderr,"IPALIAS - PIPE is full: %s (let's store it!)\n",inet_fmt(src,s1));
							fflush(stderr);

							struct droite * newdr = (struct droite *)malloc(sizeof(struct droite));
							memcpy(&(newdr->intdroite),noprobe,4);
							newdr->next = NULL; /* add at tail */

							if(!head_ipalias_son)
							{
							head_ipalias_son = newdr; /* the ll was empty */
							tail_ipalias_son = newdr;
							}
							else
							{
							tail_ipalias_son->next = newdr; /* add at the end */
							tail_ipalias_son = newdr;
							}
						}

	/*tells to my father, I don't want to see/probe this IP anymore...*/
					}

			}


		while (--ncount >= 0 && p < ep ) {

			/*RIGHT PART*/
			register u_int32 neighbor = *(u_int32*)p;
			p += 4;

			char right[IP_SIZE];
			strcpy(right,INET_FMT(neighbor, s1));

			struct droite * dr = (struct droite *)malloc(sizeof(struct droite));

			dr->intdroite = inet_addr(right);
			dr->next = nh->head_dr;
			nh->head_dr = dr;//add at the head (last in first...)



			/*recursivity: explores all routable neighbors ...*/
			if(routable(right)){

			/* TO TEST IF THE RIGHT IP HAS BEEN ALRD SEEN */
			struct confo * routoy;
			int hashy = jhash_1word(neighbor,0)%HT_LENGTH_I;
			int foundyy = 0;
			list_for_each_entry(routoy,&ALRD_SEEN[hashy],list){if(neighbor == routoy->IP){foundyy = 1;break;}};

			//printf("=> IPrec: %s %d\n",right,foundyy);

			/* not yet explored ! -> pipe to the sending father ... */
			/* IF NOT, PROBE IT */
			if(!foundyy  && rec )
			{
			u_int32 ngh = neighbor;

			char IPrec[4];
			memcpy(IPrec,&ngh,4);

			close(datapipe[0]);

			short wr = write(datapipe[1],IPrec,4);

			if(wr < 0 && errno == EAGAIN)/* the pipe is full (kernel space) => fill a linked list (user space) */
			{
				perror("write pipe error:");
				fprintf(stderr,"IPREC - PIPE is full: on %s ",inet_fmt(src,s1));
				fprintf(stderr,"%s - let's store it!\n",inet_fmt(ngh,s1));
				fflush(stderr);

				struct droite * newdr = (struct droite *)malloc(sizeof(struct droite));
				memcpy(&(newdr->intdroite),IPrec,4);
				newdr->next = NULL; /* add at tail */

				if(!head_iprec_son)
				{
			    head_iprec_son = newdr; /* the ll was empty */
				tail_iprec_son = newdr;
				}
				else
				{
				tail_iprec_son->next = newdr; /* add at the end */
				tail_iprec_son = newdr;
				}
			}


			}
			}
		}
		}
	}

}

/* to drop non globally routable addresses: return 0 if non routable, and 1 otherwise */
int routable(char * IP){

	if(!strcmp(IP,"0.0.0.0")  || !strcmp(IP,"255.255.255.255"))
	return 0;

	char one[4];
	char two[4];

	strcpy(one,"");
	strcpy(two,"");

	int i = 0;
	int j = 0;
	int nb = 0;

	while(nb < 2 && i < 8){

	if(IP[i] == '.'){nb++;j=0;}
	else if(nb == 0){one[j]=IP[i];j++;one[j]='\0';}
	else if(nb == 1){two[j]=IP[i];j++;two[j]='\0';}

	i++;

	}


	if(strcmp(one,"10") == 0)return 0;
	else if(strcmp(one,"192") == 0 && strcmp(two,"168") == 0 )return 0;
	else if(strcmp(one,"172") == 0 && strcmp(two,"16") >= 0)return 0;
	else return 1;


}

#ifdef TARGETAS

/* to know if at least one IP is in targeted ASN */
int continue_rec(u_char	*p, int datalen, u_int32 level){

	    u_char *ep = p + datalen;
	    char left[IP_SIZE];
	    int map;
	    u_int broken_cisco = ((level & 0xffff) == 0x020a); /* 10.2 */


		while (p < ep) {

			register int ncount;//number of neighbors

			register u_int32 laddr = *(u_int32*)p;
			strcpy(left,INET_FMT(laddr, s1));

			patricia_node_t* node = try_search_best(radix_tree, left);
							if (node) {
								map = (int)node->user1;
							}

							if (map == ASN) /* at least one IP belongs to the ASN*/
							return 1;

							p += 7;
							ncount = *p++;

									if (broken_cisco && ncount == 0)	/* dumb Ciscos */
									    			ncount = 1;
									if (broken_cisco && ncount > 15)	/* dumb Ciscos */
									    			ncount = ncount & 0xf;

			p += 4*ncount;


		}



		return 0; /* not a single IP in the ASN*/

}
#endif

/* to avoid duplicates alias in stange case: fragmentation+desordering or IP not in the alias*/
int hash_test(struct confo * alrs_routoy,u_int32 my_hash){
	/* in order to know if a packet as already been saw via another IP of reply */

	struct chk_sum * tmp = alrs_routoy->head_chksum;
	while(tmp){
								if(tmp->checksum_data == my_hash){return 1;}
								tmp = tmp->next;
			 }
return 0;

}

/**********************************/
/*ACCEPT CISCO FRAGMENTED PACKETS*/
/**********************************/

void
myaccept_neighbors2next(src, dst, p, datalen, level, datapipe, datapipenot, routo)
	u_int32	src, dst, level;
	u_char	*p;
	int     datalen;
	int datapipe[];
	int datapipenot[];
	struct conf * routo;
/* not the first packet, dont print header */
{
	u_char *ep = p + datalen;
	u_int broken_cisco = ((level & 0xffff) == 0x020a); /* 10.2 */
	/* well, only possibly_broken_cisco, but that's too long to type. */

#ifdef ASTARGET
short rec = continue_rec(p,datalen,level);
#elif INTERNET
short rec = 1;
#endif

    u_int skip = 0;/* to deal with stupid 3.x */

    if ((level & 0xffff) == 0x0603 || (level & 0xffff) == 0x0403 || (level & 0xffff) == 0x0803); /* dumb 3.6, 3.4 and 3.8 */
    u_int broken_junip = 1;

	while (p < ep) {
		register u_char metric;
		register u_char thresh;
		register u_char flags;
		register int ncount;
		register u_int32 laddr = *(u_int32*)p;

		char left[IP_SIZE];
		strcpy(left,INET_FMT(laddr, s1));

		p += 4;
		metric = *p++;
		thresh = *p++;
		flags = *p++;
		ncount = *p++;
		if (broken_cisco && ncount == 0)	/* dumb Ciscos */
			ncount = 1;
		if (broken_cisco && ncount > 15)	/* dumb Ciscos */
			ncount = ncount & 0xf;


		if(skip){//the right IP does not exists
							struct neighbor_head * nh;
							nh = (struct neighbor_head *)malloc(sizeof(struct neighbor_head));
							//sprintf(nh->gauche,"%s",left);

							nh->intgauche = inet_addr(left);
							nh->next = routo->nlist;
							routo->nlist = nh;//add at the head (last in first...)

							sprintf(nh->metricflags,"[%d/%d", metric, thresh);
									if (flags & DVMRP_NF_TUNNEL)
									strcat(nh->metricflags,"/t");
									if (flags & DVMRP_NF_SRCRT)
									strcat(nh->metricflags,"/s");
									if (flags & DVMRP_NF_PIM)
									strcat(nh->metricflags,"/p");
									if (flags & DVMRP_NF_QUERIER)
									strcat(nh->metricflags,"/q");
									if (flags & DVMRP_NF_DISABLED)
									strcat(nh->metricflags,"/d");
									if (flags & DVMRP_NF_DOWN)
									strcat(nh->metricflags,"/o");
									if (flags & DVMRP_NF_LEAF)
									strcat(nh->metricflags,"/l");
									strcat(nh->metricflags,"]");

							struct droite * dr = (struct droite *)malloc(sizeof(struct droite));

							//sprintf(dr->droite,"%s","#");
							dr->intdroite = 0;//inet_addr(right);
							dr->next = NULL;
							nh->head_dr = dr;//add at the head (last in first...)

				}

				else{

		struct neighbor_head * nh;
		nh = (struct neighbor_head *)malloc(sizeof(struct neighbor_head));

		nh->intgauche = inet_addr(left);
		nh->head_dr = NULL;

		nh->next = routo->nlist;
		routo->nlist = nh;//add at the head (last in first...)

		/* multicast infos */
		sprintf(nh->metricflags,"[%d/%d", metric, thresh);
		if (flags & DVMRP_NF_TUNNEL)
		strcat(nh->metricflags,"/t");
		if (flags & DVMRP_NF_SRCRT)
		strcat(nh->metricflags,"/s");
		if (flags & DVMRP_NF_PIM)
		strcat(nh->metricflags,"/p");
		if (flags & DVMRP_NF_QUERIER)
		strcat(nh->metricflags,"/q");
		if (flags & DVMRP_NF_DISABLED)
		strcat(nh->metricflags,"/d");
		if (flags & DVMRP_NF_DOWN)
		strcat(nh->metricflags,"/o");
		if (flags & DVMRP_NF_LEAF)
		strcat(nh->metricflags,"/l");
		strcat(nh->metricflags,"]");


				/*mark left address as already probed*/
				if(laddr != src && routable(left)){/* The normal way: no duplicate */

							struct confo * alrs_routoy; /* we won't send that info to the father and mark as already seen if we have already do it*/
							int hashy = jhash_1word(laddr,0)%HT_LENGTH_I;
							int foundyy = 0;
							list_for_each_entry(alrs_routoy,&ALRD_SEEN[hashy],list){if(laddr == alrs_routoy->IP ){foundyy = 1;break;}};

							if(foundyy)
							alrs_routoy->first = src;/* I am the (new) leader of this IP/alias */
							else
							{

					struct confo * router = (struct confo *)malloc(sizeof(struct confo));//put in ALRD SEEN
					int hash = jhash_1word(laddr,0)%HT_LENGTH_I;
					router->IP = laddr;
					router->first = src; /* I am the current winner*/
					list_add(&router->list,&ALRD_SEEN[hash]);

					close(datapipenot[0]);

					char noprobe[4];
					u_int32 lad = laddr;
					memcpy(noprobe,&lad,4);

					short wr = write(datapipenot[1],noprobe,4);

							if(wr < 0 && errno == EAGAIN)/* pipe is full */
							{
								perror("write pipe error:");
								fprintf(stderr,"IPALIAS - PIPE is full: %s (let's store it!)\n",inet_fmt(src,s1));
								fflush(stderr);

								struct droite * newdr = (struct droite *)malloc(sizeof(struct droite));
								memcpy(&(newdr->intdroite),noprobe,4);
								newdr->next = NULL; /* add at tail */

								if(!head_ipalias_son)
								{
								head_ipalias_son = newdr; /* the ll was empty */
								tail_ipalias_son = newdr;
								}
								else
								{
								tail_ipalias_son->next = newdr; /* add at the end */
								tail_ipalias_son = newdr;
								}
							}

					/*tells to my father, I don't want to see/probe this IP anymore...*/
							}

					}


		while (--ncount >= 0 && p < ep) {

					/*RIGHT PART*/
					register u_int32 neighbor = *(u_int32*)p;
					p += 4;

					char right[IP_SIZE];
					strcpy(right,INET_FMT(neighbor, s1));

					struct droite * dr = (struct droite *)malloc(sizeof(struct droite));

					//sprintf(dr->droite,"%s",right);
					dr->intdroite = inet_addr(right);
					dr->next = nh->head_dr;
					nh->head_dr = dr;//add at the head (last in first...)

					/*recursivity: explores all non 0.0.0.0 neighbors ...*/
					if(routable(right)){

					/* TO TEST IF THE RIGHT IP HAS BEEN ALRD SEEN */
					struct confo * routoy;
					int hashy = jhash_1word(neighbor,0)%HT_LENGTH_I;
					int foundyy = 0;
					list_for_each_entry(routoy,&ALRD_SEEN[hashy],list){if(neighbor == routoy->IP){foundyy = 1;break;}};

					/* not yet explored ! -> pipe to the sending father ... */
					/* IF NOT, PROBE IT */
					if(!foundyy  && rec )
					{
					u_int32 ngh = neighbor;
					char IPrec[4];
					memcpy(IPrec,&ngh,4);

					close(datapipe[0]);
					short wr = write(datapipe[1],IPrec,4);

					if(wr < 0 && errno == EAGAIN)/* pipe is full */
					{
						perror("write pipe error:");
						fprintf(stderr,"IPREC - PIPE is full: %s (let's store it!)\n",inet_fmt(src,s1));
						fflush(stderr);

						struct droite * newdr = (struct droite *)malloc(sizeof(struct droite));
						memcpy(&(newdr->intdroite),IPrec,4);
						newdr->next = NULL; /* add at tail */

						if(!head_iprec_son)
						{
						head_iprec_son = newdr; /* the ll was empty */
						tail_iprec_son = newdr;
						}
						else
						{
						tail_iprec_son->next = newdr; /* add at the end */
						tail_iprec_son = newdr;
						}
					}

					}
					}
		}

	  }
	}
}

int
get_number(var, deflt, pargv, pargc)
	int    *var, *pargc, deflt;
	char ***pargv;
{
	if ((*pargv)[0][2] == '\0') {	/* Get the value from the next
					 * argument */
		if (*pargc > 1 && isdigit((*pargv)[1][0])) {
			(*pargv)++, (*pargc)--;
			*var = atoi((*pargv)[0]);
			return 1;
		} else if (deflt >= 0) {
			*var = deflt;
			return 1;
		} else
			return 0;
	} else {		/* Get value from the rest of this argument */
		if (isdigit((*pargv)[0][2])) {
			*var = atoi((*pargv)[0] + 2);
			return 1;
		} else {
			return 0;
		}
	}
}

/**********************************/
/*****FILL SENDING FIELDS *********/
/**********************************/

int prepare_sending(char * IP, struct hostent *hp, struct hostent bogus, int curaddr){

	if (routable (IP) && (target_addr = inet_addr(IP)) != -1) {
					hp = &bogus;
					hp->h_length = sizeof(target_addr);
					hp->h_addr_list = (char **)malloc(2 * sizeof(char *));
					hp->h_addr_list[0] = malloc(hp->h_length);
					memcpy(hp->h_addr_list[0], &target_addr, hp->h_length);
					hp->h_addr_list[1] = 0;
				} else return 0; /* false addr */

				/* Check all addresses; mrouters often have unreachable interfaces */
				for (curaddr = 0; hp->h_addr_list[curaddr] != NULL; curaddr++) {
				    memcpy(&target_addr, hp->h_addr_list[curaddr], hp->h_length);
				    {			/* Find a good local address for us. */
					int     udp;
					struct sockaddr_in addr;
					int     addrlen = sizeof(addr);

					addr.sin_family = AF_INET;
			#if (defined(BSD) && (BSD >= 199103))
					addr.sin_len = sizeof addr;
			#endif
					addr.sin_addr.s_addr = target_addr;
					addr.sin_port = htons(2000);	/* any port over 1024 will
									 * do... */
					if ((udp = socket(AF_INET, SOCK_DGRAM, 0)) < 0
					|| connect(udp, (struct sockaddr *) & addr, sizeof(addr)) < 0
					    || getsockname(udp, (struct sockaddr *) & addr, &addrlen) < 0) {
						return 0; /* bad addr */
					}
					close(udp);
					our_addr = addr.sin_addr.s_addr;
				    }


				}

				return 1;
}


void
usage()
{


#ifdef ASTARGET
	fprintf(stderr,
		    "Usage: sudo ./mrinfo listIP fileOUTPUT radixTREE stoppingSET ASN [serverIP]\n");
#elif INTERNET
	fprintf(stderr,
		    "Usage: sudo ./mrinfo listIP fileOUTPUT\n");
#endif

exit(1);
}

/**********************************/
/****MAIN: FATHER & ITS SON********/
/**********************************/

int
main(argc, argv)
	int     argc;
	char   *argv[];
{


	struct timeval et;
	struct hostent *hp;
	struct hostent bogus;
	char *host;
	int curaddr;

	setlinebuf(stderr);

	if (geteuid() != 0) {
		fprintf(stderr, "mrinfo: must be root\n");
		exit(1);
	}



#ifdef ASTARGET
	if (argc < 6)
			usage();
#elif INTERNET
	if (argc < 3)
			usage();
#endif

	    int data_pipe[2];/* to provide new recursive IP to the father*/
	    int rcpipe = pipe(data_pipe);

	    if (rcpipe == -1) {
		perror("pipe RC");
		exit(1);
	    }

	    fcntl(data_pipe[1],F_SETFL,O_NONBLOCK);

	    int data_pipe_not[2];/* to avoid reprobing the same IP*/
	    int npipe = pipe(data_pipe_not);

	    if (npipe == -1) {
	  	perror("pipe NP");
	  	exit(1);
	  	}

	    fcntl(data_pipe_not[1],F_SETFL,O_NONBLOCK);

	    int data_pipe_probe[2];/* to inform the son with last probes*/
	    int ppipe = pipe(data_pipe_probe);

	    if (ppipe == -1) {
	  	perror("pipe PP");
	  	exit(1);
	  	}

#ifdef OLDSKL
	    int data_pipe_link[2];/* to inform the son of the last query*/
	    int lpipe = pipe(data_pipe_link);

	    if (lpipe == -1) {
	  	perror("pipe LP");
	  	exit(1);
	  	}
#endif

		init_igmp();


#ifdef ASTARGET
		radix_tree = Ip2AsMapping_tree_init(argv[3]); /* load and construct the tree for lookup */
				ASN = atoi(argv[5]);

				if(argc == 7)/* IP of the server */
				{strcpy(IPserver,argv[6]);sleep(10); /* for Pietro, he is slow */}
				else strcpy(IPserver,"");
#endif

		pid_t pid = fork();

		/*********************************/
		/* THE FATHER : it sends QUERIES */
		/*********************************/
		if(pid != 0 ){

	    int nbsend = 1;/* to count the request number !*/

		signal(SIGTSTP, close_sock);/* ALL CLOSE ON CTRL+Z */
		signal(SIGINT, SIG_IGN);/* IGNORE CTRL+C */
		signal(SIGALRM, handle_sigalrm);/* SKIP DNS ON ALARM */

		int i = 0;
		for (i=0;i<HT_LENGTH_I;i++)/* ALREADY PROBED ADDR */
		INIT_LIST_HEAD(&ALRD_SEEN[i]);



		/* SOME INIT STUFFS */
		int fileLIST = open(argv[1],O_RDONLY);

#ifdef ASTARGET
		int fileSTOP = open(argv[4],O_RDONLY);
#elif INTERNET
		int fileSTOP = 0;
#endif

		int nbuf = 1;
		int SIZE = 1;

		char IP[IP_SIZE]; /* for static/stopping set files */
		strcpy(IP,"");

		char buf[2];
		buf[0] = 'x';
		buf[1] = '\0';

		/* to eat fast recursive IPs */
		struct droite * head_iprec = NULL;
		struct droite * tail_iprec = NULL;

		struct timeval tv,tv2;

#ifdef OLDSKL
		u_int32 currenttime = (u_int32)time(0);
#else
		gettimeofday(&tv2,NULL);
		double currenttime = (double)tv2.tv_sec + 0.000001*(double)tv2.tv_usec ;
#endif


#ifdef ASTARGET

		/* NO MORE PROBE THEM: ALL IPS IN THE STOPPING SET LIST: argv[4] */

		while(nbuf != 0 && fileSTOP > 0){
		while(buf[0] != '\n'){
		nbuf = read(fileSTOP,buf,SIZE);
		if(buf[0] >= '0' && buf[0] <= '9' || buf[0] == '.')
		strcat(IP,buf);
		}

		u_int32	probed_addr = inet_addr(IP); /* put in ALRD SEEN */

		struct confp * router = (struct confp *)malloc(sizeof(struct confp));
		int hash = jhash_1word(probed_addr,0)%HT_LENGTH_I;
		router->IP = probed_addr;

#ifdef noDNS
#else
		router->dns = (char *)malloc(4*sizeof(char));
		strcpy(router->dns,"dns");
#endif
		list_add(&router->list,&ALRD_SEEN[hash]);

	    nbuf = read(fileSTOP,buf,SIZE);
	    strcpy(IP,"");

		}
		strcpy(IP,"");
#endif



		nbuf = 1;
		buf[0] = 'x';
		buf[1] = '\0';

		struct dnschain * head = NULL; /* list of IP to DNS solve */

		/* PROBE THE FIRST IP IN THE LIST: argv[1] */

		while(buf[0] != '\n'){
		nbuf = read(fileLIST,buf,SIZE);
		if(buf[0] >= '0' && buf[0] <= '9' || buf[0] == '.')
		strcat(IP,buf);
		}

		short ps = prepare_sending(IP,hp,bogus,curaddr);

#ifdef OLDSKL
		u_int32 lastrectime = (u_int32)time(0);
#else
		gettimeofday(&tv2,NULL);
		double lastrectime = (double)tv2.tv_sec + 0.000001*(double)tv2.tv_usec ;
#endif

		if(ps){
		u_int32	probed_addr = inet_addr(IP);

		ask2(probed_addr);


		printf("SEND IGMP ASK2 NEIGHBOR TO %s %d - %d\n",IP,nbsend,(u_int32)time(0));
		fflush(stdout);

		nbsend++;

	    /*mark probed address as already seen (maybe it is not on left side !) (avoid the re-probing of the same IP when dst does not apear in laddr)*/
		struct confp * router = (struct confp *)malloc(sizeof(struct confp));//put in ALRD SEEN
		int hash = jhash_1word(probed_addr,0)%HT_LENGTH_I;
		router->IP = probed_addr;

#ifdef noDNS
#else
		router->dns = (char *)malloc(4*sizeof(char));
		strcpy(router->dns,"dns");
#endif

		list_add(&router->list,&ALRD_SEEN[hash]);

#ifdef OLDSKL

		/* send the IP-in to the son*/
		lastrectime = (u_int32)time(0);
		close(data_pipe_link[0]);
		char msg[30];

		gettimeofday(&tv2,NULL);
		short sz = sprintf(msg,"%u %.0f %.0f",inet_addr(IP),(double)tv2.tv_sec,(double)tv2.tv_usec);
		//printf("%u %.0f %.0f (%d)\n",inet_addr(IP),(double)tv2.tv_sec,(double)tv2.tv_usec,sz);
		//fflush(stdout);

		write(data_pipe_link[1],msg,30); /*I inform my son that I have sent a probe*/
#endif


		}

		nbuf = 1;
		buf[0] = 'x';
		buf[1] = '\0';
	    strcpy(IP,"");

	    /* IP found by recursion */
		char IPrec[4];
	    strcpy(IPrec,"");

		annoy = 0;

		fd_set  fds;

		FD_ZERO(&fds);
		FD_SET(data_pipe[0],&fds);
		FD_SET(data_pipe_not[0],&fds);

		int max = 0;
		if(data_pipe_not[1] > data_pipe[1])
		max = data_pipe_not[1];
		else max = data_pipe[1];

		tv.tv_sec = 0;
		tv.tv_usec = 10L;

		short fdx = 0;

		//***** THE LOOP FOR RECUSIVE PROBING *****//
		for(;;){
		while(!glob_kill)
		{

		FD_ZERO(&fds);
		FD_SET(data_pipe_not[0],&fds);
		FD_SET(data_pipe[0],&fds);

		select(max + 1, &fds, 0, 0, &tv);

		tv.tv_sec = 0;
		tv.tv_usec = 10L;

#ifdef OLDSKL
		currenttime = (u_int32)time(0);
#else
		gettimeofday(&tv2,NULL);
		currenttime = (double)tv2.tv_sec + 0.000001*(double)tv2.tv_usec ;
#endif


		fdx = 0;

#ifdef DEBUG
		/* for debug */
		if(head)
		{fprintf(stderr,"SEND [%d] %d %d %d (%d) -- IP %s\n",(u_int32)time(0),FD_ISSET(data_pipe_not[0],&fds),FD_ISSET(data_pipe[0],&fds),head,glob_kill,head->name);
		fflush(stderr);
		}
		else {
		fprintf(stderr,"SEND [%d] %d %d %d (%d) -- no IP to resolve\n",(u_int32)time(0),FD_ISSET(data_pipe_not[0],&fds),FD_ISSET(data_pipe[0],&fds),head,glob_kill);
		fflush(stderr);
		}
#endif


		if(glob_kill)
		break;

		/* we prioritize the mark as alrd probed*/
		else if(FD_ISSET(data_pipe_not[0],&fds))/* alias */
		{fdx = 1; close(data_pipe_not[1]);read(data_pipe_not[0],IPrec,4);annoy = 0;}

		/* we slow down the probing while we receive left addr */
		else if(FD_ISSET(data_pipe[0],&fds))/* recursivity */
		{close(data_pipe[1]);read(data_pipe[0],IPrec,4); annoy = 0;

		struct droite * newdr = (struct droite *)malloc(sizeof(struct droite));
		memcpy(&(newdr->intdroite),IPrec,4);
		newdr->next = NULL; /* add at tail */

		//printf("<= %s\n",inet_fmt(newdr->intdroite,s1));
		//fflush(stdout);

		if(!head_iprec)
		{
	    head_iprec = newdr; /* the ll was empty */
		tail_iprec = newdr;
		}
		else
		{
		tail_iprec->next = newdr; /* add at the end */
		tail_iprec = newdr;
		}

		}

	    /* else something to read in the static file */
		else if (!head_iprec && (currenttime > lastrectime + 0.0000001*(double)TIMEINTER) && (nbuf = read(fileLIST,buf,SIZE)) > 0 ){


			//printf("%f %f %f\n",currenttime,lastrectime,0.0000001*(double)TIMEINTER);
			//fflush(stdout);


			while(buf[0] != '\n'){
					read(fileLIST,buf,SIZE);
					if(buf[0] >= '0' && buf[0] <= '9' || buf[0] == '.')
					strcat(IP,buf);
					//printf("> %s %s \n",buf,IP);
					//fflush(stdout);

					}

						short ps = prepare_sending(IP,hp,bogus,curaddr);

						if(ps){
						u_int32	probed_addr = inet_addr(IP);

						annoy = 2; /* to speed up the wait */

						//to know whether this IP has been already found
					    struct confp * routoy;
					    int hashy = jhash_1word(probed_addr,0)%HT_LENGTH_I;
						int foundyy = 0;
						list_for_each_entry(routoy,&ALRD_SEEN[hashy],list){if(routoy->IP == probed_addr){foundyy = 1;break;}};

					if(!foundyy && probed_addr != -1)
					{
					ask2(probed_addr);

					printf("SEND [1] IGMP ASK2 NEIGHBOR TO %s %d - %d %d\n",IP,nbsend,(u_int32)time(0),head);
					fflush(stdout);

					nbsend++;

#ifdef OLDSKL
lastrectime = (u_int32)time(0);
/* send the IP-in to the son*/
close(data_pipe_link[0]);
char msg[30];
gettimeofday(&tv2,NULL);
short sz = sprintf(msg,"%u %.0f %.0f\n",inet_addr(IP),(double)tv2.tv_sec,(double)tv2.tv_usec);
//printf("%u %.0f %.0f (%d)\n",inet_addr(IP),(double)tv2.tv_sec,(double)tv2.tv_usec,sz);
//fflush(stdout);
write(data_pipe_link[1],msg,30); /*I inform my son that I have sent a probe*/

/* wait a while before the next send */
//sleep(TIMEOLDSKL);
#else

					gettimeofday(&tv2,NULL);
					lastrectime = (double)tv2.tv_sec + 0.000001*(double)tv2.tv_usec ;
					close(data_pipe_probe[0]);
					write(data_pipe_probe[1],"PPP",4); /*I inform my son that I have sent a probe*/

#endif


#ifdef noDNS
//usleep(TIMEPROBESTATIC);
#else

					if(head){
					/* if there is some DNS to resolve */
					/* find the next left IP to treat */
					struct confp * router2;
					hash = jhash_1word(head->IP,0)%HT_LENGTH_I;
					int foundo = 0;
					list_for_each_entry(router2,&ALRD_SEEN[hash],list){if(router2->IP == head->IP){foundo = 1;break;}};


					if(foundo){
					annoy = 0;
					char IP_right_dns[100];

					if (!tonametime(head->name,IP_right_dns))
					sprintf(IP_right_dns,"-");



		router2->dns = (char *)malloc(strlen(IP_right_dns)*sizeof(char));
		strcpy(router2->dns,IP_right_dns);


												/*suppress it from the chain*/
												struct dnschain * tmp = head;
												head = head->next;
												free(tmp);

					}
					} //else usleep(TIMEPROBESTATIC);

#endif
				    /*mark probed address as already seen (maybe it is not on left side !) (avoid the re-probing of the same IP when dst does not apear in laddr)*/
					struct confp * router = (struct confp *)malloc(sizeof(struct confp));//put in ALRD SEEN
					int hash = jhash_1word(probed_addr,0)%HT_LENGTH_I;
					router->IP = probed_addr;

#ifdef noDNS
#else
		router->dns = (char *)malloc(4*sizeof(char));
		strcpy(router->dns,"dns");
#endif


					list_add(&router->list,&ALRD_SEEN[hash]);

				    }

						}

				    strcpy(IP,"");

		}


/* NOTHING TO DO => DNS */
#ifdef noDNS
#else
		else if(head){//we resolve DNS to do something more than sleep...
		    annoy = 1;

			struct confp * router2;/* find the left*/
			char IP_right_dns[100];// (char *)malloc(100*sizeof(char));

			int hash = jhash_1word(head->IP,0)%HT_LENGTH_I;
			int foundo = 0;
			list_for_each_entry(router2,&ALRD_SEEN[hash],list){if(router2->IP == head->IP){foundo = 1;break;}};


			if(foundo){

			// read failed so we see if it timed out
			if (! tonametime(head->name,IP_right_dns))
				sprintf(IP_right_dns,"-");

			router2->dns = (char *)malloc(strlen(IP_right_dns)*sizeof(char));
			strcpy(router2->dns,IP_right_dns);
			/*supress it from the list*/
			struct dnschain * tmp = head;
			head = head->next;
			free(tmp);

			}

		annoy = 1;
		close(data_pipe_probe[0]);
		write(data_pipe_probe[1],"DDD",4); /* I inform my son that I have some DNS to solve */
		break;
		}

#endif
		/****************************/
		/***** DEAL with SON MSG ****/
		/****************************/

		/* my son wants to kill me ?*/

		if(!strcmp(IPrec,"999"))
			{
			fprintf(stderr,"KILL msg recv by the father :) \n");
			fflush(stderr);

			glob_kill = 1;

			break;
			}

#ifdef noDNS
#else

		/* my son wants tells me the process is finished ! I can sent all my DNS info */
		else if(!strcmp(IPrec,"DNS")){

			fprintf(stderr,"DNS msg recv by the father :) \n");
			fflush(stdout);

			int sendy = 0;
			char router[120];

			if(strcmp(IPserver,"") != 0)
			sendy = 1;

			if(sendy){
			struct sockaddr_in serveur; // TCP server struct

			 sockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
			 serveur.sin_family = AF_INET;

			serveur.sin_addr.s_addr = inet_addr(IPserver);

			serveur.sin_port = htons(50007);

			if(connect(sockfd,(struct sockaddr*)&serveur,sizeof(serveur)) == -1)
			{
			perror("Connection problem: ");
			exit(2);
			}

			}

			int i; /* FLUSH all IP/DNS couple */
			struct confp * routoy;
			fdout = fopen(argv[2],"a+");
			fprintf(fdout,"***********DNS END ROUND : %d**********\n",(u_int32)time(0));

			for(i=0;i<HT_LENGTH_I;i++)
			{
				routoy = NULL;
				if(&ALRD_SEEN[i]){
							list_for_each_entry(routoy,&ALRD_SEEN[i],list){
							if(routoy){

							/* this IP is not in the topology */
						   if(routoy->dns &&  !strcmp(routoy->dns,"dns")){
						   break;
						   }

						   else{
							char dns[50];
							if((routoy->dns[0] <= '9' && routoy->dns[0] >= '1'))
							strcpy(dns,"-");
							else strcpy(dns,routoy->dns);

							//printf("%s %c => %s\n",routoy->dns,routoy->dns[0],dns);

							fprintf(fdout,"%s : %s\n",INET_FMT(routoy->IP,s1),dns);
							fflush(fdout);

							if(sendy){
								strcpy(router,"");
								sprintf(router,"%s:%s|*",INET_FMT(routoy->IP,s1),dns);

							send(sockfd,router,strlen(router),0);}

							break;
						   }
							}
							else break;
							};
						}
						}

			if(sendy){
				send(sockfd,"END|*",5,0);
				close(sockfd);
					}

			fclose(fdout);
			glob_kill = 1;

			fprintf(stderr,"DNS END => ROUND FINISH\n");
			fflush(stderr);

			break;
		}
#endif

		/* my son tells me this addr is already in a alias */
		else if(fdx == 1){

			/*char IPcop[IP_SIZE];
			int j = 1;

			while(IPrec[j] != '\0')
			{IPcop[j-1] = IPrec[j]; j++;}

			IPcop[j-1] = '\0';*/

			u_int32	probed_addr = 0;//inet_addr(IPcop);

			memcpy(&probed_addr,IPrec,4);

			//MAYBE ADD A TEST ON THE FACT THAT THIS IP MAY ALRD BE STORED via right IP (normally already done via the son ..?)
			if(probed_addr != -1){

#ifdef noDNS
#else
			//put it in the DNS list (left addr)
			struct dnschain * new = (struct dnschain *)malloc(sizeof(struct dnschain));
			strcpy(new->name,INET_FMT(probed_addr,s1));
			new->IP = probed_addr;
			new->next = head;
			head = new;
#endif

			//put it in ALRD SEEN
			struct confp * router = (struct confp *)malloc(sizeof(struct confp));//put in ALRD SEEN
			int hash = jhash_1word(probed_addr,0)%HT_LENGTH_I;
			router->IP = probed_addr;

#ifdef noDNS
#else
			router->dns = (char *)malloc(2*sizeof(char));
			strcpy(router->dns,"-");
#endif

			list_add(&router->list,&ALRD_SEEN[hash]);
								}


		}
		/* recursive IPs */
		else if (head_iprec && (currenttime > lastrectime + 0.000001*(double)TIMEINTER) ){

				//u_int32	probed_addr = 0;//inet_addr(IPrec);
				//memcpy(&probed_addr,IPrec,4);

				//printf("%f %f %f\n",currenttime,lastrectime,0.000001*(double)TIMEINTER);
				//fflush(stdout);

				//printf("<SEND= %s\n",inet_fmt(head_iprec->intdroite,s1));
				//fflush(stdout);

				u_int32	probed_addr = head_iprec->intdroite;

				struct droite * tmp = head_iprec;
				head_iprec = head_iprec->next;
				free(tmp);


				short ps = prepare_sending(INET_FMT(probed_addr,s1),hp,bogus,curaddr);

				if(ps){

				struct confp * routoy;
				int hashy = jhash_1word(probed_addr,0)%HT_LENGTH_I;
				int foundyy = 0;
				list_for_each_entry(routoy,&ALRD_SEEN[hashy],list){if(routoy->IP == probed_addr){foundyy = 1;break;}};

			    /*mark probed address as already seen (avoid the re-probing of the same IP when dst does not apear in left addr)*/
				if(!foundyy && probed_addr != -1){

			    ask2(probed_addr);

				printf("SEND [2] IGMP ASK2 NEIGHBOR TO %s %d - %d\n",INET_FMT(probed_addr,s1),nbsend,(u_int32)time(0));
				fflush(stdout);
				nbsend++;


#ifdef OLDSKL
lastrectime = (u_int32)time(0);

/* send the IP-in to the son*/
close(data_pipe_link[0]);
char msg[30];
gettimeofday(&tv2,NULL);
short sz = sprintf(msg,"%u %.0f %.0f",probed_addr,(double)tv2.tv_sec,(double)tv2.tv_usec);
//printf("%u %.0f %.0f (%d)\n",probed_addr,(double)tv2.tv_sec,(double)tv2.tv_usec,sz);
//fflush(stdout);
write(data_pipe_link[1],msg,30); /*I inform my son that I have sent a probe*/


/* wait a while before the next send */
//sleep(TIMEOLDSKL);
#else
				gettimeofday(&tv2,NULL);
				lastrectime = (double)tv2.tv_sec + 0.000001*(double)tv2.tv_usec ;
			    close(data_pipe_probe[0]);
			    write(data_pipe_probe[1],"PPP",4); /* I inform my son that I have sent a probe */

#endif

				struct confp * router = (struct confp *)malloc(sizeof(struct confp));//put in ALRD SEEN
				int hash = jhash_1word(probed_addr,0)%HT_LENGTH_I;
				router->IP = probed_addr;

/* 2 TIMEPROBE sleep if noDNS */
#ifdef noDNS
//							usleep(TIMEPROBE);
#else
							/*on the current right IP*/
							char IP_right_dns[100];

							// read failed so we see if it timed out
							if (! tonametime(INET_FMT(probed_addr,s1),IP_right_dns)) //FIRST DNS !
							sprintf(IP_right_dns,"-");
							router->dns = (char *)malloc(strlen(IP_right_dns)*sizeof(char));
							strcpy(router->dns,IP_right_dns);
#endif

							list_add(&router->list,&ALRD_SEEN[hash]);

#ifdef noDNS
//							usleep(TIMEPROBE);
#else
							if(head){
							/* find the next left IP to treat */
							struct confp * router2;
							hash = jhash_1word(head->IP,0)%HT_LENGTH_I;
							int foundo = 0;
							list_for_each_entry(router2,&ALRD_SEEN[hash],list){if(router2->IP == head->IP){foundo = 1;break;}};


							if(foundo){
							// read failed so we see if it timed out
							if (!tonametime(head->name,IP_right_dns)) //SECOND DNS !
							sprintf(IP_right_dns,"-");

							router2->dns = (char *)malloc(strlen(IP_right_dns)*sizeof(char));
							strcpy(router2->dns,IP_right_dns);

							/*suppress it from the chain*/
							struct dnschain * tmp = head;
							head = head->next;
							free(tmp);

														}
							} //else usleep(TIMEPROBE);
#endif

					    }

		}

		}
		strcpy(IPrec,"");
		strcpy(IP,"");

		}
		/* END MAIN LOOP */

		if(glob_kill)
		break;

		}
		/* EXIT */

		kill(pid,9); /*kill my son*/
		fprintf(stderr,"KILL ALL => %d %d (%d)\n",getpid(),pid,glob_kill);
		return 1;


		}

		/*********************************/
		/* THE SON : it receives REPLIES */
		/*********************************/

		else{
			/* the son */

		    int flush_pipe[2];/* the son of the son tells to its father TIME_SLICE is elapsed: the father tries to flush ...*/
		    int fpipe;
		    fpipe = pipe(flush_pipe);

		    if (fpipe == -1) {
			perror("pipe:");
			exit(4);
		    }

		    /* the son buffer to avoid blocking */
		    head_iprec_son = NULL;
		    tail_iprec_son = NULL;

		    head_ipalias_son = NULL;
		    tail_ipalias_son = NULL;

		    /* the son creates its "own son" in order to decide when flush its data*/
		    pid_t pid_f = fork();

		    		if(!pid_f){
		    //son of the son: sent a msg to its father each TIME_SLICE sec

		    			/* it ignores all SIG*/
		    			signal(SIGTSTP,SIG_IGN);
		    			signal(SIGALRM,SIG_IGN);
		    			signal(SIGINT,SIG_IGN);

		    			for(;;){
		    			sleep(SLICETIME);/* each TIME_SLICE send a msg in the pipe to its father*/

		    			close(flush_pipe[0]);
		    			write(flush_pipe[1],"XXX",4);
		    			/*send a flush sig to my father!*/
		    			}

		    			return 1;

		    		}
		    		else {
			//the receiving son

			/* counter for received packets */
			int nbnew = 0;
			int nbtot = 0;
			int nbfrag = 0;

		nb_slice = 0;

		int sendy = 0;

		if(strcmp(IPserver,"") != 0)
		sendy = 1;

		if(sendy){
	 /* this son is in charge of the TCP connection to the server */
	 struct sockaddr_in serveur;   // TCP server struct

	sockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	serveur.sin_family = AF_INET;

	serveur.sin_addr.s_addr = inet_addr(IPserver);

	  serveur.sin_port = htons(50007);

	  if(connect(sockfd,(struct sockaddr*)&serveur,sizeof(serveur)) == -1)
	  {
		perror("Connection problem: ");
		exit(2);
	  }

		}

		/* This son should flush the data /end the process on SIGINT ... */
		struct sigaction act;
		memset (&act, 0, sizeof(act));
		act.sa_handler = flush_data;

		if (sigaction(SIGINT, &act, 0)) {
			perror ("sigaction");
			return 1;
		}

		/* ... and ignore other SIG */

		signal(SIGTSTP,SIG_IGN);
		signal(SIGALRM,SIG_IGN);

		fdout = fopen(argv[2],"w+");
		fprintf(fdout,"***********NEW ROUND : %d**********\n",(u_int32)time(0));

		int i = 0;

		for (i=0;i<HT_LENGTH_A;i++)
		{
		INIT_LIST_HEAD(&hashtable[i]);
		INIT_LIST_HEAD(&ALRD_SEEN[i]);
		}

		for (i=HT_LENGTH_A;i<HT_LENGTH_I;i++)
		INIT_LIST_HEAD(&ALRD_SEEN[i]);

		fd_set  fds;

		int count, recvlen, dummy = 0;
		register u_int32 src, dst, group;
		struct ip *ip;
		struct igmp *igmp;
		int     ipdatalen, iphdrlen, igmpdatalen;

			close(flush_pipe[1]);//my son wants to know if I can flush
			close(data_pipe_probe[1]);//my father tells me it has sent a probe

		    int max;

		    if(igmp_socket > flush_pipe[0])
			max = igmp_socket;
			else
			max = flush_pipe[0];

		    if (max < data_pipe_probe[0])
		    max = data_pipe_probe[0];

#ifdef OLDSKL

		    if (max < data_pipe_link[0])
		    max = data_pipe_link[0];

		    struct link * tab_link[1000]; /* array of link towards link struct */
		    int nblink = 0; /* global index */

		    u_int32 ipin; /* the probed IP */
		    double startipin; /* the sent time (in sec)*/
		    double startipin2; /* the sent time (in usec)*/

#endif

		    struct timeval tv,tv2;
		    tv.tv_sec = 0;
		    tv.tv_usec = 10L;

		 /* Main receive loop */

		while (!glob_kill){
		//WHILE I RECEIVE REPLIES...

			FD_ZERO(&fds); /* prepare reading file descriptors */

		    FD_SET(igmp_socket,&fds);
		    FD_SET(flush_pipe[0],&fds);
		    FD_SET(data_pipe_probe[0],&fds);

#ifdef OLDSKL
		    FD_SET(data_pipe_link[0],&fds);
#endif

			select(max+1, &fds, 0, 0, &tv);
			tv.tv_sec = 0;
			tv.tv_usec = 10L;

#ifdef DEBUG
			/* for debug (use a large tv for that ...) */
			fprintf(stderr,"RECV [%d] %d %d %d (%d)\n",(u_int32)time(0),FD_ISSET(igmp_socket, &fds),FD_ISSET(flush_pipe[0], &fds),FD_ISSET(data_pipe_probe[0], &fds),nb_slice);
			fflush(stderr);
#endif

			/* to avoid blocking issues*/
			if(glob_kill)
			break;

			else
			{

#ifdef OLDSKL
			/* we receive a msg from our father */
			if(FD_ISSET(data_pipe_link[0], &fds)){

				/* This is the IP_in */
				char msg[30];
				close(data_pipe_link[1]);
				ssize_t nbb = read(data_pipe_link[0],msg,30);/* to treat this alert */

			//	printf(">|%s|\n",msg);

				ipin = (u_int32)atof(strtok(msg," "));
				startipin = atof(strtok(NULL," "));
				startipin2 = atof(strtok(NULL," "));

			//	printf(">>>|%u| |%.0f| |%.0f| (nbb_read: %d - IP: %s - time: %d)\n",ipin,startipin,startipin2,nbb,INET_FMT(ipin,s1),(int)time(0));
			//	fflush(stdout);

				nb_slice = 0;
											}
#endif


			if(FD_ISSET(igmp_socket, &fds)){
			/* we receive a packet*/

			recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE, 0, NULL, &dummy);

			/* sizeof(struct ip) 20 + 8 + 12 = 40 bytes min for one single line */
			if (recvlen > 36){

#ifdef OLDSKL
gettimeofday(&tv2,NULL); /* get the last packet arrival */

//printf("preRECV-OLDSKL-%.0f %.0f\n",(double)tv2.tv_sec,(double)tv2.tv_usec);
//fflush(stdout);
#endif

			nb_slice = 0; /* we receive a packet */

			ip = (struct ip *) recv_buf;

			src = ip->ip_src.s_addr;
			dst = ip->ip_dst.s_addr;
			iphdrlen = ip->ip_hl << 2;

#ifdef LINUX
       	         /*
        	         *      BSD mashes the IP header returned to the user, Linux
                	 *      returns it undamaged so we have to do our sums
                	 *      differently.
                 */
	                ipdatalen = ntohs(ip->ip_len);
        	        ipdatalen -= iphdrlen;
#else
			ipdatalen = ip->ip_len;
#endif

			igmp = (struct igmp *) (recv_buf + iphdrlen);
			group = igmp->igmp_group.s_addr;
			igmpdatalen = ipdatalen - IGMP_MINLEN;

			u_char data[igmpdatalen+1];/*in bytes*/
			strcpy(data,"");

			u_char IPdata[ipdatalen+1];/*in bytes*/
			strcpy(IPdata,"");

			u_char * igmp_char = (u_char *)(igmp + 1);
			u_char * ip_char = (u_char *)(ip);

			int i = 0;
			while(i < igmpdatalen){/*only IGMP data */
			data[i] = (u_char)(*(igmp_char + i));
			i++;
			}

			i = 0;
			while(i < ipdatalen){/*only IP header data */
			IPdata[i] = (u_char)(*(recv_buf + i));
			i++;
			}

			u_int32_t data_hash = jhash(data,igmpdatalen,0);
			u_int32_t IP_hash = jhash(IPdata,ipdatalen,0);

			struct confo * routoy;
			int hashy = jhash_1word(src,0)%HT_LENGTH_I;
			int foundyy = 0;

			/*Do not consider IP which has been already probed/aliased */


			list_for_each_entry(routoy,&ALRD_SEEN[hashy],list){
			if(routoy->IP == src){
			foundyy = 1;

			if(routoy->first != src) /* I am not the leader of any alias: this not my job!*/
			{foundyy = 2;break;}
			else if(!routoy->head_chksum && routoy->checksum_data == data_hash) /* first data hash packet test*/
			{foundyy = 2;break;}
			else if(routoy->head_chksum){
			/* look at all checksum in the linked list... */
			struct chk_sum * tmp = routoy->head_chksum;
			while(tmp){
				if(tmp->checksum_data == data_hash)
				{foundyy = 2;break;}
				tmp = tmp->next;
					 }
			}
			break;
			};
			}

			// => frag_code (foundyy) 0: first_time, 1: a new fragment 2: already seen (hash approx) or not alias leader
			// do not deal well with anycast addr :(


						/* new alias */
						if(!foundyy)
						nbnew++;

						/*received packet */
						nbtot++;

						/* first time we see it: new alias */
						if(!foundyy)
						{
						/* new answer: store it in the global hashtable */
						struct conf * router = (struct conf *)malloc(sizeof(struct conf));//put in ALRD SEEN
						int hash = jhash_1word(src,0)%HT_LENGTH_A;
						router->IP = src;
						router->nlist = NULL;
						router->flag = 1; /* router has been accessed in the last time slice */
						router->alrdflush = 0;
						list_add(&router->list,&hashtable[hash]);

						/* mark src address as already seen (maybe it is not on left side... !) */
						struct confo * routero = (struct confo *)malloc(sizeof(struct confo));//put in ALRD SEEN
						hash = jhash_1word(src,0)%HT_LENGTH_I;
						routero->IP = src;
						routero->checksum_data = data_hash;
						routero->head_chksum = NULL;
						routero->first = src; /*first time this IP has been seen (via itself !)*/

						list_add(&routero->list,&ALRD_SEEN[hash]);

						myaccept_neighbors2(src, dst, (u_char *)(igmp + 1),
								igmpdatalen, ntohl(group),data_pipe,data_pipe_not,router,data_hash);

						} /* a fragmented reply */
						else if (foundyy == 1){

						/* obtain the index of the alias (if the src IP is not an alias leader, skip it) */
						struct conf * routo;
						int hasho = jhash_1word(src,0)%HT_LENGTH_A;
						int foundo = 0;
						list_for_each_entry(routo,&hashtable[hasho],list)
						{if(routo->IP == src){foundo = 1;break;}};

						if(routoy->first == src && foundo) {
						/* accepted fragmented packets */
						nbfrag ++;

						routo->flag = 1; /*router has been accessed in the last time slice*/
						myaccept_neighbors2next(src, dst, (u_char *)(igmp + 1),
									igmpdatalen, ntohl(group),data_pipe,data_pipe_not,routo);

						/* add the new chechsum at the top of the list*/
						struct chk_sum * new = (struct chk_sum *)malloc(sizeof(struct chk_sum));

						new->next = routoy->head_chksum;
						new->checksum_data = data_hash;
						routoy->head_chksum = new;
										}
						/*otherwise (!foundo) this router /this left IP/ has been already seen through another replying interface /alias/*/


												}
						//fragmentation founddy == 2 --> strong proba that this packet has been already seen !
						printf("RECV MRINFO REPLY: tstp (%d) >>> sz %d-%d fr IP %s (IPchk %d) DATAchk %d frg %d [%d/%d/%d]\n",(u_int32)time(0),
														recvlen,igmpdatalen,INET_FMT(src,s1),IP_hash,data_hash,foundyy,nbnew,nbfrag,nbtot);
						fflush(stdout);


#ifdef OLDSKL
if(!foundyy){ /* a new alias */
struct link * lkinout = (struct link *)malloc(sizeof(struct link));
lkinout->IP_in = ipin;
lkinout->IP_out = src;

lkinout->diff = (double)((double)tv2.tv_sec - startipin + 0.000001*((double)tv2.tv_usec - startipin2));

tab_link[nblink] = lkinout;
nblink ++;

printf("OLDSKL [%d.%d]: %s ",(ntohl(group) & 0xff),((ntohl(group) >> 8) & 0xff),INET_FMT(lkinout->IP_in,s1));
printf("%s %f\n",INET_FMT(lkinout->IP_out,s1),(double)lkinout->diff);
fflush(stdout);

if(nblink > NBXP)
{
glob_kill = 1;
break;
}
}
#endif

			}

			}
			else if (head_ipalias_son) { /* SEND TO THE FATHER THE REMAINING ALIAS (ONE by ONE) */

				char IPtmp[4];

				memcpy(IPtmp,&(head_ipalias_son->intdroite),4);

				close(data_pipe_not[0]);
				short wr = write(data_pipe_not[1],IPtmp,4);

				if(wr < 0 && errno == EAGAIN)/* pipe is full */
				{
					perror("write pipe error:");
					fprintf(stderr,"IPALIAS - undirect mode - PIPE is full\n");
					fflush(stderr);

				} else {/* we remove the elt */

				struct droite * tmp = head_ipalias_son;
				head_ipalias_son = head_ipalias_son->next;
				free(tmp);
				}


			}

			else if (head_iprec_son) { /* SEND TO THE FATHER THE REMAINING IPREC (ONE by ONE) */

				char IPtmp[4];

				memcpy(IPtmp,&(head_iprec_son->intdroite),4);

				close(data_pipe[0]);
				short wr = write(data_pipe[1],IPtmp,4);

				if(wr < 0 && errno == EAGAIN)/* pipe is full */
				{
					perror("write pipe error:");
					fprintf(stderr,"IPREC - undirect mode - PIPE is full\n");
					fflush(stderr);
				} else {/* we remove the elt */
				struct droite * tmp = head_iprec_son;
				head_iprec_son = head_iprec_son->next;
				free(tmp);
				}


			//	printf("=IPREC> %d %s\n",wr,inet_fmt((u_int32)IPtmp,s1));
			//	fflush(stdout);

				}

/* DEAL WITH OTHER MSGS */

#ifdef OLDSKL
#else
			/* we receive a msg from our father */
			if(FD_ISSET(data_pipe_probe[0], &fds)){

				/* Is it time for stopping ?*/
				char msg[4];
				close(data_pipe_probe[1]);
				read(data_pipe_probe[0],msg,4);/* to treat this alert */

				if(!strcmp(msg,"PPP") || !strcmp(msg,"DDD"))
				nb_slice = 0;
				/* a probe has been sent, I wait ... */
				/* or some DNS are performed, wait for them ... */

											}

#endif

#ifdef OLDSKL
#else

			 /* we receive a msg from our son */
			if(FD_ISSET(flush_pipe[0], &fds)){

				/* Is it time for a flushing try ?*/
				char msg[4];
				close(flush_pipe[1]);
				read(flush_pipe[0],msg,4);
				/* to treat this alert */


				if(!strcmp(msg,"XXX"))
				flush_data(0); // to send or not ...


				if(!FD_ISSET(data_pipe_probe[0], &fds) && nb_slice > NBSLICE){// if the process is finished, then ask the father to flush DNS entries
#ifdef noDNS
#else
				close(data_pipe_not[0]);
				write(data_pipe_not[1],"DNS",4);

				close(data_pipe[0]);
				write(data_pipe[1],"DNS",4);

				fprintf(stderr,"DNS msg to the father %d\n",nb_slice);
				fflush(stdout);

				sleep(SLICETIME); /* to ensure the correct reception of the DNS msg */
#endif

				glob_kill = 1;
				break;

				}

											}
#endif //OLDSKL

			}

		    }


		if (glob_kill) /* I receive a SIGINT signal */
		{
			/* kill my son */
			kill(pid_f,9);

			/*kill my father and myself !*/
			close(data_pipe_not[0]);
			write(data_pipe_not[1],"999",4);

			close(data_pipe[0]);
			write(data_pipe[1],"999",4);

			fprintf(stderr,"DEATH msg to the father %d\n",nb_slice);
			fflush(stdout);

			sleep(SLICETIME); /* to ensure the correct reception of the DEATH msg */

			return 1;
		}

		}
	}

}


#ifdef LINUX

/* dummies */
void accept_probe(src, dst, p, datalen, level)
	u_int32 src, dst, level;
	char *p;
	int datalen;
{
}
void accept_group_report(src, dst, group, r_type)
	u_int32 src, dst, group;
	int r_type;
{
}
void accept_neighbor_request2(src, dst)
	u_int32 src, dst;
{
}
void accept_report(src, dst, p, datalen, level)
	u_int32 src, dst, level;
	char *p;
	int datalen;
{
}
void accept_neighbor_request(src, dst)
	u_int32 src, dst;
{
}
void accept_prune(src, dst, p, datalen)
	u_int32 src, dst;
	char *p;
	int datalen;
{
}
void accept_graft(src, dst, p, datalen)
	u_int32 src, dst;
	char *p;
	int datalen;
{
}
void accept_g_ack(src, dst, p, datalen)
	u_int32 src, dst;
	char *p;
	int datalen;
{
}
void add_table_entry(origin, mcastgrp)
	u_int32 origin, mcastgrp;
{
}
void check_vif_state()
{
}
void accept_leave_message(src, dst, group)
	u_int32 src, dst, group;
{
}
void accept_mtrace(src, dst, group, data, no, datalen)
	u_int32 src, dst, group;
	char *data;
	u_int no;
	int datalen;
{
}
void accept_membership_query(src, dst, group, tmo)
	u_int32 src, dst, group;
	int tmo;
{
}
void accept_info_request(src, dst, p, datalen)
	u_int32 src, dst;
	u_char *p;
	int datalen;
{
}
void accept_info_reply(src, dst, p, datalen)
	u_int32 src, dst;
	u_char *p;
	int datalen;
{
}
#elif BSD

/* dummies */
void accept_probe(src, dst, p, datalen, level)
	u_int32 src, dst, level;
	char *p;
	int datalen;
{
}
void accept_group_report(src, dst, group, r_type)
	u_int32 src, dst, group;
	int r_type;
{
}
void accept_neighbor_request2(src, dst)
	u_int32 src, dst;
{
}
void accept_report(src, dst, p, datalen, level)
	u_int32 src, dst, level;
	char *p;
	int datalen;
{
}
void accept_neighbor_request(src, dst)
	u_int32 src, dst;
{
}
void accept_prune(src, dst, p, datalen)
	u_int32 src, dst;
	char *p;
	int datalen;
{
}
void accept_graft(src, dst, p, datalen)
	u_int32 src, dst;
	char *p;
	int datalen;
{
}
void accept_g_ack(src, dst, p, datalen)
	u_int32 src, dst;
	char *p;
	int datalen;
{
}
void add_table_entry(origin, mcastgrp)
	u_int32 origin, mcastgrp;
{
}
void check_vif_state()
{
}
void accept_leave_message(src, dst, group)
	u_int32 src, dst, group;
{
}
void accept_mtrace(src, dst, group, data, no, datalen)
	u_int32 src, dst, group;
	char *data;
	u_int no;
	int datalen;
{
}
void accept_membership_query(src, dst, group, tmo)
	u_int32 src, dst, group;
	int tmo;
{
}
void accept_info_request(src, dst, p, datalen)
	u_int32 src, dst;
	u_char *p;
	int datalen;
{
}
void accept_info_reply(src, dst, p, datalen)
	u_int32 src, dst;
	u_char *p;
	int datalen;
{
}


/*
 * Log errors and other messages to stderr, according to the severity of the
 * message and the current debug level.  For errors of severity LOG_ERR or
 * worse, terminate the program.
 */
void
logit(int severity, int syserr, const char *format, ...)
{
        va_list ap;

        switch (debug) {
        case 0:
                if (severity > LOG_WARNING)
                        return;
        case 1:
                if (severity > LOG_NOTICE)
                        return;
        case 2:
                if (severity > LOG_INFO)
                        return;
        default:
                if (severity == LOG_WARNING)
                        fprintf(stderr, "warning - ");
                va_start(ap, format);
                vfprintf(stderr, format, ap);
                va_end(ap);
                if (syserr == 0)
                        fprintf(stderr, "\n");
                else
                        fprintf(stderr, ": %s\n", strerror(syserr));
        }

        if (severity <= LOG_ERR)
                exit(1);
}

void
accept_neighbors(u_int32_t src, u_int32_t dst, u_char *p, int datalen,
                 u_int32_t level)
{

}

void
accept_neighbors2(u_int32_t src, u_int32_t dst, u_char *p, int datalen,
                  u_int32_t level)
{

}

#endif
